from django import forms
from django.contrib.auth import get_user_model

User = get_user_model()
from .models import VerificationCode


class RegistrerForm(forms.Form):
    username = forms.CharField(max_length=10, required=True, min_length=2, error_messages={
        'required': '请传入用户名',
        'min_length': '用户名长度在2-20之间',
        'max_length': '用户名长度在2-20之间'
    })
    password = forms.CharField(max_length=10, required=True, min_length=6, error_messages={
        'required': '请传入密码',
        'min_length': '密码长度在3-20之间',
        'max_length': '密码长度在3-20之间'
    })

    email = forms.EmailField(min_length=10, max_length=20, error_messages={
        'required': "请输入邮箱",
        'min_length': '邮箱长度在10-20',
        'max_length': '邮箱长度在10-20'
    })

    captcha = forms.CharField(max_length=4, min_length=4)

    def clean_email(self):
        email = self.cleaned_data.get('email')
        exists = User.objects.filter(email=email).exists()
        if exists:
            raise forms.ValidationError("该邮箱已经注册!")
        return email

    def clean_captcha(self):
        email = self.cleaned_data.get('email')
        captcha = self.cleaned_data.get('captcha')
        captcha_model = VerificationCode.objects.filter(email=email, code=captcha).first()
        if not captcha_model:
            raise forms.ValidationError("验证码和邮箱不匹配!")
        captcha_model.delete()
        return captcha


class LoginForm(forms.Form):
    username = forms.CharField(required=True)
    password = forms.CharField(required=True)
    remember_me = forms.IntegerField(required=False)
